import { DatePicker, Input, Select } from '@/components/AntdProxy';
import CommonDrawer from '@/components/CommonDrawer';
import { CrudFormLayout } from '@/components/Crud';
import {
  DriverSelect,
  LineSelect,
  VehicleSelect,
} from '@/components/CustomForm';
import { TRIP_STATE_OPTIONS } from '@/constants/enums';
import { REQUIRED } from '@/constants/rules';
import request from '@/utils/request';
import { useAsyncEffect, useRequest } from 'ahooks';
import { Button, Descriptions, Form, message } from 'antd';
import dayjs from 'dayjs';

const TIME_FIELDS = [
  'tripTime',
  'beginTime',
  'inLoadTime',
  'outLoadTime',
  'inUnloadTime',
  'outUnloadTime',
  'endTime',
];

const Save = (props) => {
  const { open, record, onCancel, onOk } = props;
  const [form] = Form.useForm();

  const { data: systemData, runAsync } = useRequest(
    async (params) =>
      request({
        url: record?.tripId
          ? '/datas/through/trip/line/stations'
          : '/datas/through/trip/vehicle/line/stations',
        method: 'GET',
        params,
      }),
    { manual: true },
  );

  useAsyncEffect(() => {
    if (open && record) {
      const formData = {
        ...record,
      };
      TIME_FIELDS.forEach((key) => {
        if (formData[key]) {
          formData[key] = formData[key] ? dayjs(formData[key]) : undefined;
        }
      });
      form?.setFieldsValue(formData);
      runAsync({ tripId: record.tripId });
    }
  }, [open, record]);

  const vehicleId = Form.useWatch('vehicleId', form);
  const lineId = Form.useWatch('lineId', form);
  const tripTime = Form.useWatch('tripTime', form);

  useAsyncEffect(() => {
    if (!record?.tripId && vehicleId && lineId && tripTime) {
      runAsync({
        vehicleId,
        lineId,
        tripTime: tripTime?.format?.('YYYY-MM-DD HH:mm:ss'),
      });
    }
  }, [vehicleId, lineId, tripTime, record?.tripId]);

  const handleFill = () => {
    const formData = {};
    if (systemData?.loadDriverId) {
      formData.loadDriverId = systemData?.loadDriverId;
    }
    if (systemData?.unloadDriverId) {
      formData.unloadDriverId = systemData?.unloadDriverId;
    }
    if (systemData?.tripTime) {
      formData.tripTime = dayjs(systemData?.tripTime);
    }
    if (systemData?.beginTime) {
      formData.beginTime = dayjs(systemData?.beginTime);
    }
    if (systemData?.inLoadTime) {
      formData.inLoadTime = dayjs(systemData?.inLoadTime);
    }
    if (systemData?.outLoadTime) {
      formData.outLoadTime = dayjs(systemData?.outLoadTime);
    }
    if (systemData?.inUnloadTime) {
      formData.inUnloadTime = dayjs(systemData?.inUnloadTime);
    }
    if (systemData?.outUnloadTime) {
      formData.outUnloadTime = dayjs(systemData?.outUnloadTime);
    }
    if (systemData?.endTime) {
      formData.endTime = dayjs(systemData?.endTime);
    }
    form.setFieldsValue(formData);
  };

  const handleOk = async () => {
    const values = await form.validateFields();
    console.log('values', values);
    const url = record ? '/datas/trip/update' : '/datas/trip/add';
    const params = {
      ...values,
    };
    TIME_FIELDS.forEach((key) => {
      if (params[key]) {
        params[key] = params[key].format('YYYY-MM-DD HH:mm:ss');
      }
    });
    if (record) {
      params.tripId = record?.tripId;
    }
    await request({
      url,
      method: 'POST',
      data: params,
    });
    message.success('操作成功');
    onOk?.();
  };

  const items = [
    { key: '1', label: '装车司机', children: systemData?.loadDriverName },
    { key: '2', label: '卸车司机', children: systemData?.unloadDriverName },
    { key: '3', label: '派单时间', children: systemData?.tripTime },
    { key: '4', label: '开始时间', children: systemData?.beginTime },
    { key: '5', label: '进货时间', children: systemData?.inLoadTime },
    { key: '6', label: '出货时间', children: systemData?.outLoadTime },
    { key: '7', label: '进卸货地时间', children: systemData?.inUnloadTime },
    { key: '8', label: '出卸货地时间', children: systemData?.outUnloadTime },
    { key: '9', label: '结束时间', children: systemData?.endTime },
  ];

  return (
    <CommonDrawer
      title={record ? '编辑趟次' : '新建趟次'}
      open={open}
      onClose={onCancel}
      onOk={handleOk}
      afterOpenChange={(visible) => {
        if (!visible) {
          form.resetFields();
        }
      }}
      width={1200}
      destroyOnHidden
    >
      <Form form={form} layout="vertical">
        <CrudFormLayout itemMinWidth={250}>
          <Form.Item
            label="状态"
            name="state"
            rules={[REQUIRED]}
            initialValue={99}
          >
            <Select
              allowClear={false}
              options={TRIP_STATE_OPTIONS}
              placeholder="请选择状态"
            />
          </Form.Item>
          <Form.Item label="车辆" name="vehicleId" rules={[REQUIRED]}>
            <VehicleSelect placeholder="请选择车辆" />
          </Form.Item>
          <Form.Item label="线路名称" name="lineId" rules={[REQUIRED]}>
            <LineSelect placeholder="请选择线路" />
          </Form.Item>
          <Form.Item label="装车司机" name="loadDriverId">
            <DriverSelect placeholder="请选择装车司机" />
          </Form.Item>
          <Form.Item label="卸车司机" name="unloadDriverId">
            <DriverSelect placeholder="请选择卸车司机" />
          </Form.Item>
          <Form.Item label="派单时间" name="tripTime" rules={[REQUIRED]}>
            <DatePicker
              needConfirm={false}
              placeholder="请选择派单时间"
              showTime
            />
          </Form.Item>
          <Form.Item label="开始时间" name="beginTime">
            <DatePicker
              needConfirm={false}
              placeholder="请选择开始时间"
              showTime
            />
          </Form.Item>
          <Form.Item label="进货时间" name="inLoadTime">
            <DatePicker
              needConfirm={false}
              placeholder="请选择进货时间"
              showTime
            />
          </Form.Item>
          <Form.Item label="出货时间" name="outLoadTime">
            <DatePicker
              needConfirm={false}
              placeholder="请选择出货时间"
              showTime
            />
          </Form.Item>
          <Form.Item label="进卸货地时间" name="inUnloadTime">
            <DatePicker
              needConfirm={false}
              placeholder="请选择进卸货地时间"
              showTime
            />
          </Form.Item>
          <Form.Item label="出卸货地时间" name="outUnloadTime">
            <DatePicker
              needConfirm={false}
              placeholder="请选择出卸货地时间"
              showTime
            />
          </Form.Item>
          <Form.Item label="结束时间" name="endTime">
            <DatePicker
              needConfirm={false}
              placeholder="请选择结束时间"
              showTime
            />
          </Form.Item>
        </CrudFormLayout>
        <Form.Item label="备注" name="remark">
          <Input.TextArea maxLength={150} rows={3} />
        </Form.Item>
      </Form>
      <Descriptions title="系统数据采集" items={items} />
      <Button type="primary" style={{ marginTop: 16 }} onClick={handleFill}>
        一键填充
      </Button>
    </CommonDrawer>
  );
};

export default Save;
